package com.xiaoai.httpClientTestService.httpclient.javaf;

import com.alibaba.fastjson.JSONObject;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;

import java.io.IOException;

public class HttpclientPostParamJson {

    public static void main(String[] args) throws IOException, ParseException {
        // 创建httpget对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 创建请求对象 设置url
        HttpPost httpPost = new HttpPost("http://localhost:8080/test/getpPostParamJson");

        // ---请求头设置传参格式
        httpPost.setHeader("Content-Type", ContentType.APPLICATION_JSON.toString());

        // ---创建传递参数
        JSONObject param = new JSONObject();
        param.put("name","xiaoai");
        param.put("sex","nan");
        StringEntity StringEntity = new StringEntity(param.toString());

        // ---设置表单的Entity对象到post请求
        httpPost.setEntity(StringEntity);

        CloseableHttpResponse response = null;
        // 发起请求，获取response
        response = httpClient.execute(httpPost);
        // 解析
        if (response.getCode() == 200){
            String content  = EntityUtils.toString(response.getEntity(),"utf8");
            System.out.println(content);
        }
        response.close();
        httpClient.close();
    }
}
